# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

"""表达式语句发射器 - 迁移自IRExpressionStatement的render方法"""


from mcpy.ir.statements.expression import IRExprStmt
from ..core.emitter import EmitResult, NodeTypeEmitter
from ..core.context import CodeGenContext
from ..core.generator import get_global_generator


class ExpressionEmitter(NodeTypeEmitter):
    """处理表达式语句的发射器

    迁移自IRExpressionStatement.render方法，支持：
    - 普通表达式语句：expr;
    - 模块级文档字符串的过滤
    """

    def __init__(self):
        super().__init__([IRExprStmt])

    def emit(self, node: IRExprStmt, context: CodeGenContext) -> EmitResult:
        """生成表达式语句代码

        迁移自IRExpressionStatement.render方法
        """
        # 检查是否为模块级文档字符串（字符串常量表达式语句）
        if (
            hasattr(node.expr, "node_type")
            and node.expr.node_type == "constant"
            and isinstance(getattr(node.expr, "value", None), str)
        ):
            # 模块级文档字符串不生成任何 C++ 代码
            return EmitResult(code="", precedence=0)

        generator = get_global_generator()

        try:
            expr_code = generator.generate_expression(expr=node.expr, context=context)
        except Exception:
            # 如果生成失败，回退到字符串表示
            expr_code = str(node.expr)

        # 如果表达式代码为空，则不生成任何内容
        if not expr_code or expr_code.strip() == "":
            return EmitResult(code="", precedence=0)

        code = f"{expr_code};"

        return EmitResult(code=code, precedence=0)

    def get_priority(self) -> int:
        """获取发射器优先级"""
        return 30  # 较高优先级，确保表达式语句被正确处理
